#include <QtScript>
#include <QMainWindow>
#include <QApplication>
#include <QFile>
#include <QDir>
#include <QSettings>
#include <QDebug>
#include <QySciLexer>
#include <QyScript>

#include "QyConfigurator.h"
#include "QyLexerConfigurator.h"
#include "QySciEditConfigurator.h"

Q_DECLARE_METATYPE(QySciLexer*)
Q_SCRIPT_DECLARE_QMETAOBJECT( QySciLexer, QObject* )

QyConfigurator::QyConfigurator( QMainWindow * mainWindow, const QString & path )
	: QObject(mainWindow)
{

	lexerConfigurator = new QyLexerConfigurator(this);
	sciEditConfigurator = new QySciEditConfigurator(this);

	p_script = new QyScript(this);
	p_path = ( path.isEmpty() ? ( QDir::homePath() + "/." + QApplication::applicationName() ) : path );
	p_mainWindow = mainWindow;

	QDir dir(p_path);
	if ( !dir.exists() )
		dir.mkpath(p_path);

	configureScript(p_script);

	qDebug() << "Config path:" << p_path;

}

void QyConfigurator::restoreSettings() {

	QSettings qs( p_path + "/general.ini", QSettings::IniFormat );

	if (p_mainWindow) {

		if ( p_mainWindow->restoreGeometry( qs.value("mainwindow/geometry").toByteArray() ) )
			p_mainWindow->show();
		else
			p_mainWindow->showMaximized();

		p_mainWindow->restoreState( qs.value("mainwindow/state").toByteArray() );

	}

	p_initScriptFileName = p_path + "/" + qs.value( "script/initScript", "init.qs" ).toString();
	p_lastSessionFileName = p_path + "/" + qs.value( "sessions/last", "lastsession.ini" ).toString();

	runInitScript();

	emit loadPlugins( qs.value( "plugins/path", p_path + "/plugins" ).toString() );
	emit restoreSession(p_lastSessionFileName);

}

void QyConfigurator::saveSettings() {

	QSettings qs( p_path + "/general.ini", QSettings::IniFormat );

	if (p_mainWindow) {

		qs.setValue( "mainwindow/state", p_mainWindow->saveState() );
		qs.setValue( "mainwindow/geometry", p_mainWindow->saveGeometry() );

	}

	emit saveSession(p_lastSessionFileName);

}

void QyConfigurator::runInitScript() {

	if ( QFile::exists(p_initScriptFileName) ) {

		if ( p_script->evaluateFile(p_initScriptFileName) )
			emit initScriptComplete();

	}

}

void QyConfigurator::configureScript( QyScript * script ) {

	QY_SCRIPT_REGISTER_QOBJECTBASETYPE( (*script), QySciLexer );

	script->addGlobalObject( p_mainWindow, "mainWindow" );
	script->addGlobalObject( lexerConfigurator, "lexerConfigurator" );
	script->addGlobalObject( sciEditConfigurator, "sciEditConfigurator" );

}
